package com.hongshu.web.service.recommendation;

import com.hongshu.web.auth.AuthContextHolder;
import com.hongshu.web.service.recommendation.model.UserProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 用户画像服务
 * 负责用户画像的构建、更新和查询
 *
 * @author hongshu
 * @date 2024/01/01
 */
@Service
@Slf4j
public class UserProfileService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    /**
     * 获取当前用户画像
     */
    public UserProfile getCurrentUserProfile() {
        try {
            String userId = AuthContextHolder.getUserId();
            return getUserProfile(userId);
        } catch (Exception e) {
            log.error("获取当前用户画像异常", e);
            return UserProfile.defaultProfile();
        }
    }

    /**
     * 获取指定用户画像
     */
    public UserProfile getUserProfile(String userId) {
        try {
            log.info("获取用户画像: {}", userId);
            // 1. 从缓存获取
            UserProfile cachedProfile = getCachedUserProfile(userId);
            if (cachedProfile != null) {
                return cachedProfile;
            }
            // 2. 构建用户画像
            UserProfile profile = buildUserProfile(userId);
            // 3. 缓存用户画像
            cacheUserProfile(userId, profile);
            return profile;
        } catch (Exception e) {
            log.error("获取用户画像异常: userId={}", userId, e);
            return UserProfile.defaultProfile();
        }
    }

    /**
     * 构建用户画像
     */
    private UserProfile buildUserProfile(String userId) {
        UserProfile.UserProfileBuilder builder = UserProfile.builder().userId(userId);
        // 1. 基础信息
        builder.age(getUserAge(userId))
                .gender(getUserGender(userId))
                .location(getUserLocation(userId));
        // 2. 行为统计
        builder.behaviorCount(getUserBehaviorCount(userId))
                .likedItems(getUserLikedItems(userId))
                .followingUsers(getUserFollowingUsers(userId));
        // 3. 兴趣标签
        builder.interestTags(getUserInterestTags(userId))
                .tagPreferences(getUserTagPreferences(userId));
        // 4. 用户状态
        builder.isNewUser(isNewUser(userId))
                .isActiveUser(isActiveUser(userId));
        return builder.build();
    }

    /**
     * 获取用户年龄
     */
    private Integer getUserAge(String userId) {
        String key = "user_age:" + userId;
        return (Integer) redisTemplate.opsForValue().get(key);
    }

    /**
     * 获取用户性别
     */
    private String getUserGender(String userId) {
        String key = "user_gender:" + userId;
        return (String) redisTemplate.opsForValue().get(key);
    }

    /**
     * 获取用户位置
     */
    private String getUserLocation(String userId) {
        String key = "user_location:" + userId;
        return (String) redisTemplate.opsForValue().get(key);
    }

    /**
     * 获取用户行为计数
     */
    private int getUserBehaviorCount(String userId) {
        String key = "user_behavior_count:" + userId;
        Long count = (Long) redisTemplate.opsForValue().get(key);
        return count != null ? count.intValue() : 0;
    }

    /**
     * 获取用户喜欢的物品
     */
    private List<String> getUserLikedItems(String userId) {
        String key = "user_liked_items:" + userId;
        @SuppressWarnings("unchecked")
        List<String> items = (List<String>) redisTemplate.opsForValue().get(key);
        return items != null ? items : new ArrayList<>();
    }

    /**
     * 获取用户关注的人
     */
    private List<String> getUserFollowingUsers(String userId) {
        String key = "user_following:" + userId;
        @SuppressWarnings("unchecked")
        List<String> users = (List<String>) redisTemplate.opsForValue().get(key);
        return users != null ? users : new ArrayList<>();
    }

    /**
     * 获取用户兴趣标签
     */
    private List<String> getUserInterestTags(String userId) {
        String key = "user_interest_tags:" + userId;
        @SuppressWarnings("unchecked")
        List<String> tags = (List<String>) redisTemplate.opsForValue().get(key);
        return tags != null ? tags : new ArrayList<>();
    }

    /**
     * 获取用户标签偏好
     */
    private Map<String, Double> getUserTagPreferences(String userId) {
        Map<String, Double> preferences = new HashMap<>();
        String keyPrefix = "user_realtime_interest:" + userId + ":";
        Set<String> keys = redisTemplate.keys(keyPrefix + "*");
        if (keys != null) {
            for (String key : keys) {
                String tag = key.substring(keyPrefix.length());
                Double score = (Double) redisTemplate.opsForValue().get(key);
                if (score != null) {
                    preferences.put(tag, score);
                }
            }
        }
        return preferences;
    }

    /**
     * 判断是否为新用户
     */
    private boolean isNewUser(String userId) {
        int behaviorCount = getUserBehaviorCount(userId);
        return behaviorCount < 10;
    }

    /**
     * 判断是否为活跃用户
     */
    private boolean isActiveUser(String userId) {
        int behaviorCount = getUserBehaviorCount(userId);
        return behaviorCount > 50;
    }

    /**
     * 获取缓存的用户画像
     */
    private UserProfile getCachedUserProfile(String userId) {
        try {
            String key = "user_profile:" + userId;
            @SuppressWarnings("unchecked")
            Map<String, Object> cachedData = (Map<String, Object>) redisTemplate.opsForValue().get(key);
            if (cachedData != null) {
                return UserProfile.builder()
                        .userId(userId)
                        .age((Integer) cachedData.get("age"))
                        .gender((String) cachedData.get("gender"))
                        .location((String) cachedData.get("location"))
                        .behaviorCount((Integer) cachedData.get("behaviorCount"))
                        .likedItems((List<String>) cachedData.get("likedItems"))
                        .followingUsers((List<String>) cachedData.get("followingUsers"))
                        .interestTags((List<String>) cachedData.get("interestTags"))
                        .tagPreferences((Map<String, Double>) cachedData.get("tagPreferences"))
                        .isNewUser((Boolean) cachedData.get("isNewUser"))
                        .isActiveUser((Boolean) cachedData.get("isActiveUser"))
                        .build();
            }
            return null;
        } catch (Exception e) {
            log.error("获取缓存用户画像异常", e);
            return null;
        }
    }

    /**
     * 缓存用户画像
     */
    private void cacheUserProfile(String userId, UserProfile profile) {
        try {
            String key = "user_profile:" + userId;

            Map<String, Object> cacheData = new HashMap<>();
            cacheData.put("age", profile.getAge());
            cacheData.put("gender", profile.getGender());
            cacheData.put("location", profile.getLocation());
            cacheData.put("behaviorCount", profile.getBehaviorCount());
            cacheData.put("likedItems", profile.getLikedItems());
            cacheData.put("followingUsers", profile.getFollowingUsers());
            cacheData.put("interestTags", profile.getInterestTags());
            cacheData.put("tagPreferences", profile.getTagPreferences());
            cacheData.put("isNewUser", profile.isNewUser());
            cacheData.put("isActiveUser", profile.isActiveUser());

            // 缓存1小时
            redisTemplate.opsForValue().set(key, cacheData, 1, TimeUnit.HOURS);
            log.debug("用户画像缓存完成: userId={}", userId);
        } catch (Exception e) {
            log.error("缓存用户画像异常", e);
        }
    }

    /**
     * 更新用户画像
     */
    public void updateUserProfile(String userId, UserProfile profile) {
        try {
            // 更新缓存
            cacheUserProfile(userId, profile);
            log.info("用户画像更新完成: userId={}", userId);
        } catch (Exception e) {
            log.error("更新用户画像异常", e);
        }
    }

    /**
     * 清除用户画像缓存
     */
    public void clearUserProfileCache(String userId) {
        try {
            String key = "user_profile:" + userId;
            redisTemplate.delete(key);
            log.info("用户画像缓存清除完成: userId={}", userId);
        } catch (Exception e) {
            log.error("清除用户画像缓存异常", e);
        }
    }
}













